﻿using Host.Domain;
using Host.InfrasIntructure.Interface;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Host.InfrasIntructure.Implement
{
    public class DatabaseContext : IDatabaseContext
    {
        public SqlSugarScope sqlSugar { get; }
        public SqlSugarScope sqlSugarScope => throw new NotImplementedException();
        public DatabaseContext(IConfiguration configuration)
        {

            sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                ConnectionString = configuration.GetConnectionString("conn"),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
        }
        public void InitializeDatabase()
        {
            try
            {
                sqlSugar.CodeFirst.InitTables(
               typeof(Alarms),
                typeof(Devices),
                typeof(OperationLogs),
               typeof(SensorData),
              typeof(Stations),
              typeof(Users)
           
                );

                Console.WriteLine("数据库表初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw;
            }
        }
    }
}
